package javaTec.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Created by yangshunxing on 2017/9/5.
 */
public class LazyInitHolderSingleton {
    private static volatile LazyInitHolderSingleton instance;

    private LazyInitHolderSingleton() {
    }
    public static LazyInitHolderSingleton getInstance(){
        if (instance == null){
            synchronized (LazyInitHolderSingleton.class){
//                if(instance == null) {
                    instance = new LazyInitHolderSingleton();
//                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Vector<LazyInitHolderSingleton> singletons = addSingletons();
        for (int i = 0; i < singletons.size()-1; i++){
            if(!singletons.get(i).equals(singletons.get(i+1))){
                System.out.println("存在不一样的实例");
            }
        }
        System.out.println(singletons.size());
        System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
    }

    public static Vector<LazyInitHolderSingleton> addSingletons() throws InterruptedException{
        Vector<LazyInitHolderSingleton> singletons = new Vector<>();
        Thread[] threads = new Thread[100000];

        for (int i = 0; i < threads.length; i++){
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                        singletons.addElement(LazyInitHolderSingleton.getInstance());
                }
            });
        }
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        return singletons;
    }
}
